package com.willian.andrappfw.network;

import android.content.Intent;
import android.widget.Toast;

import com.willian.andrappfw.R;
import com.willian.andrappfw.activity.LoginActivity;
import com.willian.andrappfw.utils.Utils;

import java.net.ConnectException;

import retrofit2.HttpException;

public abstract class WBaseCallback<T> extends Callback<WBaseResponse<T>> {

    @Override
    public final void onSuccess(WBaseResponse<T> baseResponse) {
        if (baseResponse != null && baseResponse.isSuccess() && baseResponse.getCode() == 200) {
            onSucceed(baseResponse.getData());
        } else {
            onFailure(null);
        }
    }

    @Override
    public final void onError(Throwable throwable) {
        onFailure(throwable);
    }

    public abstract void onSucceed(T data);

    public void onFailure(Throwable throwable) {
        if (throwable instanceof ConnectException) {
            Toast.makeText(Utils.getApplicationContext(), Utils.getString(R.string.please_check_the_network), Toast.LENGTH_SHORT).show();
        } else if (throwable instanceof HttpException && ((HttpException) throwable).code() == 403) {
            Utils.getApplicationContext().startActivity(new Intent(Utils.getApplicationContext(), LoginActivity.class));
        } else {
            Toast.makeText(Utils.getApplicationContext(), Utils.getApplicationContext().getString(R.string.exception_occurred), Toast.LENGTH_SHORT).show();
        }
    }
}
